public class ReverseKGroup {
    public static void main(String[] args) {

    }
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            if(getLength(head) < k){
                return head;
            }
            return reverseKGroupMerge(head,k);

        }
        public ListNode reverseKGroupMerge(ListNode head, int k){
            if(head == null || getLength(head) < k){
                return head;
            }

            ListNode prev = null;
            ListNode cur = head;
            for(int i = 0; i < k; i++){
                ListNode temp = head.next;
                cur.next = prev;
                prev = cur;
                cur = temp;
            }
            ListNode newHead = prev;
            head.next = reverseKGroupMerge(cur,k);
            return newHead;
        }
        public int getLength(ListNode head){
            int count = 0;
            ListNode cur = head;
            while(cur != null){
                count++;
                cur = cur.next;
            }
            return count;
        }
    }
}
